package cocma;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Random;
import helper.Config;

public class Chromosome implements Cloneable{
    private Random random = Config.getSalt();

    private BitSet dna;
    private int length;
    public int length(){
        return length;
    }



    public Chromosome(int length) {
        dna = new BitSet(length);
        this.length = length;
    }
    public void setAllele(int index, boolean value){
        dna.set(index, value);
    }
        public boolean  getAllele(int index){
       return dna.get(index);
    }

    public void mutatate() {
        int point = random.nextInt(length);
        dna.set(point, !dna.get(point));
    }



    public List<Chromosome> singlePointCrossover(Chromosome parent2){

         int point = 1 + random.nextInt(length -1);
        Chromosome child1 = new Chromosome(length);
        Chromosome child2 = new Chromosome(parent2.length);

        for (int i=0; i < dna.length(); i++){
            if (i < point){
                child1.setAllele(i, getAllele(i));
                child2.setAllele(i, parent2.getAllele(i));
            }else{
                child1.setAllele(i, parent2.getAllele(i));
                child2.setAllele(i, getAllele(i));
            }
        }
        List<Chromosome> children = new ArrayList(2);
        children.add(child1);
        children.add(child2);
        return children;
    }

    @Override
    protected Object clone(){
        Chromosome clone = new Chromosome(length);
        clone.dna = (BitSet) dna.clone();
        return clone;
    }


        @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < length; j++) {
            sb.append(dna.get(j) ? "1 " : "0 ");
        }
        sb.append("\n");
        return sb.toString();
    }


}
